<template>
  <div class="wrapper-left">
    <div class="dept-select">
      <el-cascader
      :append-to-body="false"
        :style="{ width: width }"
        v-model="deptId"
        :options="deptOptions"
        :props="{ checkStrictly: true }"
        ref="cascader"
        @change="handleChange"
        placeholder="请选择所属部门"
      >
      </el-cascader>
      <Title
        :title="'业务实时发展量'"
        style="text-align: left; margin-bottom: 3px;"
      />
    </div>

    <div class="bar-svg">
      <div
        class="bar-svg-item"
        v-for="(item, index) in marketingBusinessList"
        :key="index"
      >
        <div class="bar-svg-item-left">
          <div class="bar-svg-item-title">{{ item.title }}</div>
          <div class="bar-svg-item-num">
            {{ item.num }}<span style="font-size: 18px">个</span>
          </div>
        </div>

        <div class="task-item-piechart">
          <!-- <ProportionPieChart :value="item.taskProgress" :color="item.color"></ProportionPieChart> -->
          <el-progress
            :width="70"
            :stroke-width="8"
            type="circle"
            :percentage="item.percentage"
            :color="colorList[index]"
            text-color="#000"
            :format="format"
          ></el-progress>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getDeptTree } from "@/api/system/user";
import { countPackageType } from "@/api/home";
import { topTotal } from "@/api/api";
import Title from "../Title";
import store from "@/store";
const widthCache = {};
export default {
  name: "HomeLeft",
  dicts: ["package_type"],
  components: {
    Title,
  },
  props:{
    targetTime: null
  },
  watch: {
    targetTime: function (newVal, oldVal) {
      if(newVal == null || newVal == "") {
        this.postData.targetTime = this.formatDate();
      }
      else{
        this.postData.targetTime = newVal;
      } 
      this.getTopTotal(this.postData)
    }
  },
  data() {
    return {
      //cascader: null,
      width: "160px",
      deptId: 100,
      deptOptions: [],
      postData: {
        // deptId: 219,
        deptId: store.state.user.deptId, //将缓存的用户id赋值给userId，用于查询营销人员
        targetTime: this.formatDate(),
      },
      colorList: [
        "#34C758",
        "#FD4F4F",
        "#FFBF6B",
        "#2871FF",
        "#81B337",
        "#75F9FD",
        "#B886F8",
        "#91C5FD",
        "#7F83F7",
        "#FD4F4F",
      ],

      //营销业务统计列表
      //全量融合 宽带 fttr  视频AI   质差修复 老旧终端升级 老旧套餐升级
      marketingBusinessList: [
        {
          title: "全量融合",
          num: 0,
          percentage: 0,
        },
        {
          title: "宽带",
          num: 0,
          percentage: 0,
        },

        {
          title: "FTTR",
          num: 0,
          percentage: 0,
        },
        {
          title: "视频AI",
          num: 0,
          percentage: 0,
        },
        {
          title: "老旧终端升级",
          num: 0,
          percentage: 0,
        },
        {
          title: "老旧套餐升级",
          num: 0,
          percentage: 0,
        },
        {
          title: "核券量",
          num: 0,
          percentage: 0,
        },
      ],
      // marketingBusinessList: [
      //   {
      //     title: "全量融合",
      //     num: 40,
      //     percentage: 60,
      //   },
      //   {
      //     title: "宽带",
      //     num: 34,
      //     percentage: 50,
      //   },

      //   {
      //     title: "FTTR",
      //     num: 20,
      //     percentage: 60,
      //   },
      //   {
      //     title: "视频AI",
      //     num: 15,
      //     percentage: 33.33,
      //   },
      //   {
      //     title: "老旧终端升级",
      //     num: 10,
      //     percentage: 60,
      //   },
      //   {
      //     title: "老旧套餐升级",
      //     num: 10,
      //     percentage: 40,
      //   },
      //   {
      //     title: "核券量",
      //     num: 40,
      //     percentage: 80,
      //   },
      // ],
    };
  },
  created() {
    this.getTopTotal(this.postData);
    this.getDeptTree(this.deptId);
  },
  methods: {
    formatDate(date = new Date()) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /** 查询部门下拉树结构 */
    async getDeptTree(deptId) {
      getDeptTree({ deptId: deptId }).then((response) => {
        console.log(response.data, "response");
        // this.deptOptions = response.data;
        if (deptId == 100) {
          var treeData = response.data.children;
          treeData.map((item) => {
            item.label = item.deptName;
            item.value = item.deptId;
            if (item.children && item.children.length) {
              item.children.forEach((child) => {
                child.label = child.deptName;
                child.value = child.deptId;
                if (child.children && child.children.length) {
                  child.children.forEach((grandson) => {
                    grandson.label = grandson.deptName;
                    grandson.value = grandson.deptId;
                    delete grandson.children;
                  });
                }
              });
            }
          });
          this.deptOptions = {
            label: response.data.deptName,
            value: response.data.deptId,
            children: treeData,
          };
          // console.log(this.deptOptions, "deptOptions");
        }
      });
    },
    handleChange(value) {
      // const deptId = value[value.length - 1];
      this.postData.deptId = value[value.length - 1];
      this.getTopTotal(this.postData);
       /* console.log(value, "value");
      console.log(value[1], "value");
      
     let nodesInfo = this.$refs.cascader
        .getCheckedNodes()[0]
        .pathLabels.join("/").length;
      console.log(
        this.$refs.cascader.getCheckedNodes()[0].pathLabels.join("/"),
        "zifuchuan长度"
      );
      console.log(nodesInfo, "nodesInfo"); */
      // 获取级联选择器选中的名称数组
      if (value) {
        //   const labelsLength = $refs.cascader.getCheckedNodes()[0]
        // .text.split("/")
        // .join("").length;
        var str = this.$refs.cascader.getCheckedNodes()[0].pathLabels.join("/");
        /* console.log(this.getTextWidthUsingDOM(str,"20px SourceHanSansSC-regular"), "str");
        //var width = this.getTextWidth(str, "16px") + 140;
        const lenLength = this.$refs.cascader
          .getCheckedNodes()[0]
          .pathLabels.join("/").length;
        console.log(lenLength, "lenLength");
        //this.width = lenLength * 10 + 140 + "px"; */
        this.width =
          this.getTextWidthUsingDOM(str, "20px SourceHanSansSC-regular") +
          62 +
          "px";
      } else {
        this.width = "160px";
      }
      //this.form.deptId = value[1];
    },
    getTextWidth(text, font) {
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      context.font = font;
      const metrics = context.measureText(text);
      return metrics.width;
    },
    getTextWidthUsingDOM(text, font) {
      const element = document.createElement("span");

      element.style.font = font;

      element.style.visibility = "hidden";

      element.style.whiteSpace = "nowrap";

      element.textContent = text;

      document.body.appendChild(element);

      const width = element.offsetWidth;

      document.body.removeChild(element);

      return width;
    },

    getCachedTextWidth(text, font) {
      const cacheKey = `${text}-${font}`;

      if (widthCache[cacheKey]) {
        return widthCache[cacheKey];
      }

      const width = this.getTextWidth(text, font);

      widthCache[cacheKey] = width;

      return width;
    },
    // 获取字符串的像素长度
    getPixelLength(str) {
      // 创建一个隐藏的<span>元素
      var hiddenSpan = document.createElement("span");
      hiddenSpan.style.visibility = "hidden";
      hiddenSpan.style.whiteSpace = "nowrap";
      hiddenSpan.style.position = "absolute";

      // 将要测量的字符串设置为<span>元素的文本内容
      hiddenSpan.innerText = str;

      // 将<span>元素添加到文档中
      document.body.appendChild(hiddenSpan);

      // 返回<span>元素的像素宽度
      var pixelLength = hiddenSpan.offsetWidth;

      // 从文档中移除<span>元素
      document.body.removeChild(hiddenSpan);

      return pixelLength;
    },
    getTopTotal(query) {
        topTotal(query).then((res) => {
          let tempData = res.data;
          this.marketingBusinessList[0].num = tempData.top[0]?.fullFusions ?? 0;
          this.marketingBusinessList[1].num = tempData.top[0]?.broadbands ?? 0;
          this.marketingBusinessList[2].num = tempData.top[0]?.fttrs ?? 0;
          this.marketingBusinessList[3].num = tempData.top[0]?.videoAis ?? 0;
          this.marketingBusinessList[4].num = tempData.top[0]?.termUps ?? 0;
          this.marketingBusinessList[5].num = tempData.top[0]?.comboUp ?? 0;
          this.marketingBusinessList[6].num = tempData.top[0]?.popAssesss ?? 0;
          this.marketingBusinessList[0].percentage = this.calculatePercentage(
            tempData.top[0]?.fullFusions?? 0,
            tempData.total[0]?.convergenceTarget?? 0
          );
          this.marketingBusinessList[1].percentage = this.calculatePercentage(
            tempData.top[0]?.broadbands?? 0,
            tempData.total[0]?.singleBroadbandTarget?? 0
          );
          this.marketingBusinessList[2].percentage = this.calculatePercentage(
            tempData.top[0]?.fttrs?? 0,
            tempData.total[0]?.fttrTarget?? 0
          );
          this.marketingBusinessList[3].percentage = this.calculatePercentage(
            tempData.top[0]?.videoAis?? 0,
            tempData.total[0]?.videoAiPackage?? 0
          );
          this.marketingBusinessList[4].percentage = this.calculatePercentage(
            tempData.top[0]?.termUps??  0,
            tempData.total[0]?.oldTerminalUpgrade?? 0
          );
          this.marketingBusinessList[5].percentage = this.calculatePercentage(
            tempData.top[0]?.comboUp?? 0,
            tempData.total[0]?.oldPackageUpgrade?? 0
          );
          this.marketingBusinessList[6].percentage = this.calculatePercentage(
            tempData.top[0]?.popAssesss?? 0,
            tempData.total[0]?.qualityRepair?? 0
          );
        });
      },
    calculatePercentage(a, b) {
      // 处理除数为0和空的情况，还有a为0的情况
      // if (b === 0 ) {
      //   return "0.00";
      // }
      if (b === 0 || a === 0 || b == "") {
        return "0.00";
      }
      // 使用整数运算避免浮点误差
      const percentage = Math.round((a * 10000) / b);
      // 格式化为两位小数的百分比字符串
      const integerPart = Math.floor(percentage / 100);
      const decimalPart = String(percentage % 100).padStart(2, "0");

      return `${integerPart}.${decimalPart}`;
    },
    format(percentage) {
      return `${percentage}%`;
    },
  },
};
</script>

<style scoped lang="scss">
.wrapper-left {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  .dept-select {
    display: flex;
    justify-content: start;
    align-items: center;
    margin-bottom: 3px;
    .el-cascader {
      width: auto;
    }
  }
}

.filtr-selects {
  display: flex;
  justify-content: end;
}

.bar-svg {
  height: 70%;
  display: flex;
  // flex-direction: column;
  justify-content: space-between;

  .bar-svg-item {
    // margin-top: 8px;
    display: flex;
    align-items: center;
    width: 100%;

    .bar-svg-item-left {
      width: 110px;
      text-align: right;
      margin-right: 5px;
      line-height: 30px;
    }

    .bar-svg-item-title {
      font-size: 16px;
      color: #3dc8fd;
    }

    .bar-svg-item-num {
      display: flex;
      justify-content: end;
      font-size: 28px;
      line-height: 35px;
      color: #000;
      font-weight: 600;
    }
  }
}

::v-deep .el-progress--circle .el-progress__text {
  font-size: 16px !important;
  font-family: SourceHanSansSC-regular !important;
  font-weight: bold !important;
}
::v-deep .el-input--suffix .el-input__inner {
  // padding-right: 15px;
  color: #409eff;
  font-size: 20px;
  font-family: SourceHanSansSC-regular;
  font-weight: 600;
}
@media (max-width: 768px) {
  .bar-svg {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
  }

  .bar-svg-item {
    margin-bottom: 20px;
  }
}
</style>
